package com.perkinelmer.housecall.client.activities.capture;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.perkinelmer.housecall.client.activities.capture.Capture.CaptureCompleteCallback;
import com.perkinelmer.housecall.client.activities.capture.Capture.CaptureId;
import com.perkinelmer.housecall.client.activities.patientdetails.PatientDetailsActivity;
import com.perkinelmer.housecall.client.activity.Activity;
import com.perkinelmer.housecall.client.activity.ActivityManager;
import com.perkinelmer.housecall.client.model.Observation;

public class CaptureActivity implements Activity<CaptureId>, CaptureCompleteCallback {

	public static final ActivityId<CaptureId> ID = ActivityId.make("capture");
	
	private final Map<CaptureId,Capture> captureMap = new HashMap<CaptureId,Capture>();
	private final Panel capturePanel;
	private final PatientDetailsActivity detailsActivity;
	private final ActivityManager manager;
	
	public CaptureActivity(CaptureLibrary library, PatientDetailsActivity detailsActivity, ActivityManager manager) {
		for(Capture capture : library.getCaptures()) {
			captureMap.put(capture.getId(), capture);
		}
		
		capturePanel = new VerticalPanel();
		this.manager = manager;
		this.detailsActivity = detailsActivity;
	}
	
	@Override
	public ActivityId<CaptureId> getId() {return ID;}

	@Override
	public void start(Panel panel, CaptureId id) {
		Capture capture = getCapture(id);
		panel.add(capturePanel);
		
		capture.start(capturePanel, new CaptureParameter(this));
	}

	@Override
	public void stop() {
		capturePanel.clear();
	}

	private Capture getCapture(CaptureId id) {
		return captureMap.get(id);
	}

	@Override
	public void captureComplete(Observation observation) {
		detailsActivity.addObservation(observation);
		manager.gotoActivity(PatientDetailsActivity.ID, detailsActivity.getPatient());
	}
	
	@Override
	public void captureCanceled() {
		manager.gotoActivity(PatientDetailsActivity.ID, detailsActivity.getPatient());
	}
}
